package com.cl.security.system.service;

import com.cl.security.common.email.service.SendMailService;
import com.cl.security.common.result.CommonResult;
import com.cl.security.system.entity.RegisterEmail;
import com.cl.security.system.repository.RegisterEmailRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

@Service
public class RegisterEmailService {
    @Autowired
    private RegisterEmailRepository registerEmailRepository;
    @Autowired
    private UserService userService;


    public CommonResult send(RegisterEmail registerEmail) {
        if (userService.emailRegistered(registerEmail.getEmail())) {
            return CommonResult.failed("该邮箱已被注册");
        }
        RegisterEmail oldEmail = findByEmail(registerEmail);
        Integer code = (int) ((Math.random() * 9 + 1) * 100000);
        if (oldEmail == null) {
            registerEmail.setCode(code);
            registerEmailRepository.save(registerEmail);
        } else {
            Long retryTime = System.currentTimeMillis() - oldEmail.getUpdateTime();
            Long seconds = ( 60 * 1000 - retryTime) / 1000;
            if (seconds > 0) {
                return CommonResult.failed("请" + seconds + "秒后重试");
            }
            oldEmail.setCode(code);
            registerEmailRepository.save(oldEmail);
            SendMailService.sendEmail("mall-注册验证码", "您的验证码是：" + code, "mall-admin", new String[]{" :" + oldEmail.getEmail()}, null, null);
        }
        return CommonResult.success(null,"发送成功");
    }

    public CommonResult exam(RegisterEmail registerEmail) {
        RegisterEmail registerEmailSource = findByEmail(registerEmail);
        try {
            if (registerEmail.getCode().equals(registerEmailSource.getCode())) {
                return CommonResult.success(true);
            }
        }catch (NullPointerException e) {
            return CommonResult.success(false);
        }
        return CommonResult.success(false);

    }

    private RegisterEmail findByEmail(RegisterEmail registerEmail) {
        Specification<RegisterEmail> specification = (Specification<RegisterEmail>) ((root, cq, cb) -> {
            cq.where(
                    cb.and(
                            cb.equal(root.get("email"), registerEmail.getEmail())
                    )
            );
            return cq.getRestriction();
        });
        return registerEmailRepository.findOne(specification).orElse(null);
    }

}
